package org.apache.lucene.demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.LongField;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

public class IndexFiles {
    
	/**
	 * 传入file生成索引文件
	 * @param writer
	 * @param file ,必须是一个常规可读文件
	 * @throws IOException
	 */
	protected void indexDoc(IndexWriter writer,Path file) throws IOException {
		Field field = null;
		String path = file.toString();
		Long modified = Files.getLastModifiedTime(file).toMillis();
		Reader reader = new BufferedReader(new InputStreamReader(Files.newInputStream(file), StandardCharsets.UTF_8));
		Document doc = new Document();
		field = new StringField("path", path, Field.Store.YES);
		doc.add(field);
		field = new LongField("modified", modified, Field.Store.YES);
		doc.add(field);
		field = new TextField("contents", reader);
		doc.add(field);
		writer.addDocument(doc);
	}
    
	/**
	 * 从dir目录下面开始读取文件，然后生成索引文件
	 * @param writer
	 * @param dir
	 * @throws IOException
	 */
	protected void indexDocs(final IndexWriter writer,Path dir) throws IOException {
		if(Files.isDirectory(dir)) {
			Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {
				@Override
				public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
					indexDocs(writer, file);
					return FileVisitResult.CONTINUE;
				}
			});
		} else {
			this.indexDoc(writer, dir);
		}
	}
	
	/**
	 * 读取docPath目录下面的文件，生成索引文件到indexPath
	 * @param docPath
	 * @param indexPath
	 * @throws IOException 
	 */
	public void index(String docPath,String indexPath) throws IOException {
		Analyzer analyzer = new StandardAnalyzer();
		IndexWriterConfig config = new IndexWriterConfig(analyzer);
		
		final Path docDir = Paths.get(docPath);
		Directory indexDir = FSDirectory.open(Paths.get(indexPath));
		IndexWriter writer = new IndexWriter(indexDir, config);
		indexDocs(writer,docDir);
	}
	
}
